import 'braft-editor/dist/index.css';
import React from 'react';
import {connect} from 'react-redux';
import action from '../../store/actions/generatingGoods';
import BraftEditor from 'braft-editor';
import './BraftEditor.scss';

class myBraftEditor extends React.Component {

  state = {
    editorState: BraftEditor.createEditorState(''), // 设置编辑器初始内容
    outputHTML: ''
  };

  componentDidMount() {
    this.isLivinig = true;
    let timer = setInterval(() => {
      const {isEdit, tempParameter} = this.props;
      if (isEdit && tempParameter) {
        clearInterval(timer);
        this.setState(prevState => {
          return {
            editorState: BraftEditor.createEditorState(tempParameter)
          };
        });
      }
    }, 100);
  }

  getBase64 = img => {
    const getBase64Image = img => {
      var canvas = document.createElement('canvas');
      canvas.width = img.width;
      canvas.height = img.height;
      var ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0, img.width, img.height);
      var ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase();
      var dataURL = canvas.toDataURL('image/' + ext);
      return dataURL;
    };
    var image = new Image();
    image.src = img;
    image.setAttribute('crossOrigin', 'anonymous'); //允许图片跨域请求、必须后台也允许
    //   image.onload = () => {
    var base64 = getBase64Image(image);
    // console.log(base64)
    return base64;
    //   }
  };

  componentWillUnmount() {
    this.isLivinig = false;
  }

  handleChange = editorState => {
    this.setState({
      editorState: editorState,
      outputHTML: editorState.toHTML()
    });
    this.props.BRAFT_EDITOR_CONTENT(editorState.toHTML());
    console.log('***************************************', this.state.editorState, this.state.outputHTML);
  };

  setEditorContentAsync = () => {
    this.isLivinig && this.setState({
      editorState: BraftEditor.createEditorState('<p>你好，<b>世界!</b><p>')
    });
  };

  render() {

    const {editorState, outputHTML} = this.state;

    return (
      <div>
        <div className="editor-wrapper">
          <BraftEditor
            value={editorState}
            onChange={this.handleChange}
          />
        </div>
        <h5>输出内容</h5>
        <div className="output-content">{outputHTML}</div>
      </div>
    );
  }
}

const mapStateFromToProps = state => state.generatingGoods;
export default connect(mapStateFromToProps, action)(myBraftEditor);
